import { Flex, Divider, message, Skeleton } from "antd";
import { useState, useRef, useEffect } from "react";
import { PPXinWenCard } from "./PPXinWenCard";
import {
  SITES_URL,
  sortByOrder,
  PAGE_SIZE,
  processCurrentPage,
} from "../Common/commonData";
import InfiniteScroll from "react-infinite-scroll-component";
import { thepaper } from "@/servers/crawler";

export function PPXinWen({ initData }) {
  const [messageApi, contextHolder] = message.useMessage();
  const pageTotal = useRef(initData.initHotData?.total);
  const [hotRankings, setHotRankings] = useState([]);

  const isLoading = useRef(false);
  const scrollContainerRef = useRef(null);
  const cardRef = useRef(null);

  const fetchMoreData = async (pageSize = PAGE_SIZE) => {
    if (isLoading.current || hotRankings.length >= pageTotal.current) return;
    isLoading.current = true;

    const [currentPage, currentPageSize] = processCurrentPage(
      pageSize,
      pageTotal.current,
      hotRankings
    );

    try {
      const newData = await thepaper.getHotPage(currentPage, currentPageSize);
      if (!newData.items) return;
      sortByOrder(newData?.items);

      pageTotal.current = newData.total;
      // 获得剩余所有数据
      if (currentPageSize === newData?.total) {
        newData.items = newData?.items?.slice(
          hotRankings.length,
          newData?.total
        );
      }
      if (
        newData.items === hotRankings.slice(-newData?.items, hotRankings.length)
      )
        return;
      pageTotal.current = newData?.total;
      setHotRankings((prev) => prev.concat(newData?.items));
    } catch (e) {
      messageApi.error("热榜数据加载失败");
    } finally {
      isLoading.current = false;
    }
  };

  // 1. 监听窗口大小变化，并调整容器高度
  useEffect(() => {
    const handleResize = () => {
      if (isLoading.current) return;

      const windowHeight = window.innerHeight;
      const cardHeight = cardRef?.current?.clientHeight || 100;
      const containerHeight = cardHeight * hotRankings?.length;
      const cardNum =
        Math.ceil((windowHeight - containerHeight) / cardHeight / 10) * 10;
      if (cardNum >= 10 && containerHeight < windowHeight) {
        fetchMoreData(cardNum);
      }
    };

    // 首次加载时执行
    handleResize();

    // 监听窗口变化
    window.addEventListener("resize", handleResize);

    // 组件卸载时移除监听
    return () => {
      window.removeEventListener("resize", handleResize);
    };
    // 依赖 hotRankings 确保数据更新后重新计算, 依赖isLoading否则会初始加载两次
  }, [isLoading.current, hotRankings.length]);

  return (
    <div ref={scrollContainerRef}>
      {contextHolder}
      <Divider style={{ margin: "0" }} />
      <InfiniteScroll
        dataLength={hotRankings.length}
        next={fetchMoreData}
        hasMore={hotRankings.length < pageTotal.current}
        loader={
          <Skeleton
            avatar
            paragraph={{ rows: 1 }}
            active
            style={{ padding: 12 }}
          />
        }
        endMessage={
          <a target="_blank" href={SITES_URL.ppXinWen}>
            <Divider plain>查看更多</Divider>
          </a>
        }
        scrollableTarget="scrollableDiv">
        <Flex vertical={true}>
          {hotRankings.map((v, i) => (
            <div ref={i === 0 ? cardRef : null} key={"澎湃新闻热榜" + i}>
              <PPXinWenCard
                item={v}
                style={{
                  borderRadius: `${
                    i === hotRankings.length - 1 && "0 0 0.3rem 0.3rem"
                  }`,
                }}
              />
              <Divider style={{ margin: "0" }} />
            </div>
          ))}
        </Flex>
      </InfiniteScroll>
    </div>
  );
}
